/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.dianlan.processor.business;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import info.peigen.hotpot.component.gateway.core.util.HexUtil;
import info.peigen.hotpot.component.gateway.dianlan.annotations.DianlanProtocolParse;
import info.peigen.hotpot.component.gateway.dianlan.facade.command.order.DianlanStubCostOrder;
import info.peigen.hotpot.component.gateway.dianlan.facade.enums.DianlanFrameSign;
import info.peigen.hotpot.component.gateway.dianlan.facade.enums.DianlanTransResultSign;
import info.peigen.hotpot.component.gateway.dianlan.processor.AbstractDianlanProcessor;
import info.peigen.hotpot.component.gateway.dianlan.protocol.Dianlan;
import info.peigen.hotpot.component.gateway.dianlan.protocol.passive.DianlanTransInformation;
import info.peigen.hotpot.component.gateway.dianlan.protocol.passive.DianlanTransInformationResponse;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.smartboot.socket.MessageProcessor;
import org.smartboot.socket.StateMachineEnum;
import org.smartboot.socket.transport.AioSession;

/**
 * <b>(DianlanTransInformationProcessor)</b>
 *
 * @author czj
 * @version 1.0.0
 * @since 2023/2/8
 */
@Component("DianlanTransInformationProcessor")
@Slf4j
public class DianlanTransInformationProcessor<T> extends AbstractDianlanProcessor implements MessageProcessor<T> {

    @Override
    public void process(AioSession session, Object obj) {
        Dianlan                 dianlan          = (Dianlan) obj;
        DianlanTransInformation transInformation = DianlanProtocolParse.deserialization(dianlan.getData(), DianlanTransInformation.class);
        if (StrUtil.equals(transInformation.getChargingPortNo(), IGNORE_PORT)) {
            ignorePort(dianlan);
            return;
        }

        log.info("Data:" + JSON.toJSONString(transInformation));
        DianlanStubCostOrder order = BeanUtil.copyProperties(transInformation, DianlanStubCostOrder.class);
        order.setConsumeAmount(HexUtil.parseIntAsIntel(order.getConsumeAmount()) / 10000f + "");
        order.setTotalCurrent(HexUtil.parseIntAsIntel(order.getTotalCurrent()) / 10000f + "");

        dianlan.setFrameSign(DianlanFrameSign.TransInformationResponse);
        DianlanTransInformationResponse response = DianlanTransInformationResponse.builder()
                .transNo(transInformation.getTransNo())
                .authSign(DianlanTransResultSign.Success).build();

        response(dianlan, response);
        write(session, dianlan);
        dianlanServiceFacade.cost(order);
    }

    @Override
    public void stateEvent(AioSession session, StateMachineEnum stateMachineEnum, Throwable throwable) {
        MessageProcessor.super.stateEvent(session, stateMachineEnum, throwable);
    }
}